# scripts/run_analysis.py
import sys
import os
import time
import json
import logging
from pathlib import Path

# 确保优先导入项目本地包
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from akshare_finance.models import Company
from akshare_finance.fetcher import FinancialDataFetcher
from akshare_finance.analyzer import FinancialDataAnalyzer
from akshare_finance.exporter import ExcelExporter
from akshare_finance.reporter import ConsoleReporter
from akshare_finance.pipeline import collect_all_sectors_data
from akshare_finance.dupont import DupontAnalyzer

# 简化日志配置
logging.basicConfig(
    level=logging.WARNING, format="%(levelname)s - %(message)s"  # 默认只显示警告和错误
)

# 默认配置
DEFAULT_METRICS = ["销售毛利率", "销售净利率"]
DEFAULT_PERIODS = ["20250331", "20241231", "20240630", "20231231", "20230630"]
DEFAULT_SECTORS_FILE = "scripts/sectors.json"
DEFAULT_OUTPUT_DIR = "output"


def load_sectors_config(file_path: str) -> dict:
    """加载板块配置"""
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return {
            sector: [Company(symbol=c["symbol"], name=c["name"]) for c in companies]
            for sector, companies in data.items()
        }
    except Exception as e:
        print(f"❌ 加载板块配置失败: {e}")
        sys.exit(1)


def check_api_status(fetcher):
    """检查API状态"""
    print("🔍 检查API连接状态...")
    test_symbols = ["000001", "600000", "600519"]  # 测试几个知名股票

    for symbol in test_symbols:
        try:
            df = fetcher.get_financial_abstract(symbol)
            if not df.empty:
                print(f"✅ API正常 (测试股票: {symbol})")
                return True
        except Exception:
            continue

    print("❌ API连接异常，可能原因:")
    print("   1. 网络连接问题")
    print("   2. akshare服务临时不可用")
    print("   3. 请求频率过高被限流")
    print("   建议: 稍后重试或使用 --cache 选项")
    return False


def main():
    """主函数，简化版"""
    import argparse

    parser = argparse.ArgumentParser(description="A股财务分析工具")
    parser.add_argument("--output", "-o", default=DEFAULT_OUTPUT_DIR, help="输出目录")
    parser.add_argument(
        "--sectors", "-s", default=DEFAULT_SECTORS_FILE, help="板块配置文件"
    )
    parser.add_argument("--cache", action="store_true", help="启用缓存")
    parser.add_argument("--verbose", "-v", action="store_true", help="显示详细信息")
    parser.add_argument("--skip-check", action="store_true", help="跳过API状态检查")

    args = parser.parse_args()

    # 设置日志级别
    if args.verbose:
        logging.getLogger().setLevel(logging.INFO)

    # 创建输出目录
    os.makedirs(args.output, exist_ok=True)

    print("🚀 开始分析...")

    # 加载配置
    sectors_map = load_sectors_config(args.sectors)
    print(f"📊 加载 {len(sectors_map)} 个板块")

    # 初始化组件
    fetcher = FinancialDataFetcher(
        enable_cache=args.cache, max_retries=5, retry_delay=2.0
    )

    # API状态检查
    if not args.skip_check:
        if not check_api_status(fetcher):
            print("\n⚠️  继续运行可能会遇到大量错误")
            response = input("是否继续? (y/N): ").lower().strip()
            if response != "y":
                print("已取消运行")
                sys.exit(0)

    analyzer = FinancialDataAnalyzer(
        metrics=DEFAULT_METRICS, time_periods=DEFAULT_PERIODS
    )
    reporter = ConsoleReporter(quiet=True, silent=not args.verbose)
    exporter = ExcelExporter(output_dir=args.output, time_periods=DEFAULT_PERIODS)
    dupont_analyzer = DupontAnalyzer(top_n=5, fetcher=fetcher)

    # 执行分析（减少并发数避免API限流）
    workers = 1 if not args.cache else 2  # 无缓存时使用单线程，有缓存时允许少量并发
    all_sectors_data = collect_all_sectors_data(
        sectors_map, workers, fetcher, analyzer, dupont_analyzer, reporter
    )

    # 导出结果
    output_file = exporter.export_all_sectors(all_sectors_data)

    # 统计分析结果
    total_companies = sum(len(companies) for companies in sectors_map.values())
    successful_companies = 0

    for sector_name, (sector, companies_data, sector_stats) in all_sectors_data.items():
        for company_name, (
            financial_df,
            business_df,
            dupont_basic,
            dupont_advanced,
        ) in companies_data.items():
            if financial_df is not None and not financial_df.empty:
                successful_companies += 1

    success_rate = (
        (successful_companies / total_companies * 100) if total_companies > 0 else 0
    )
    print(f"✅ 分析完成，结果已保存至: {output_file}")
    print(f"📊 成功率: {successful_companies}/{total_companies} ({success_rate:.1f}%)")


if __name__ == "__main__":
    start_time = time.time()
    try:
        main()
        elapsed = round(time.time() - start_time, 1)
        print(f"⏱️  总用时: {elapsed} 秒")
    except KeyboardInterrupt:
        print("\n⚠️  用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"❌ 运行失败: {e}")
        sys.exit(1)
